<template>
  <div>
    <el-button
      :style="buttonStyle"
      @click="dialogVisible = true"
    >
      {{ buttonText }}
    </el-button>
    <el-dialog
      v-model="dialogVisible"
      append-to-body
      :title="dialogTitle"
      width="500"
      :before-close="handleClose"
      :style="dialogStyle"
    >
      <slot name="body" />
      <template #footer>
        <div>
          <el-button @click="handleClose">
            取消
          </el-button>
          <el-button
            :loading="submitLoading"
            type="primary"
            @click="handleSubmit"
          >
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
onMounted(() => {
})

const props = defineProps({
  buttonText: {
    type: String,
    default: '没有设置按钮文本'
  },
  dialogTitle: {
    type: String,
    default: '没有设置按钮文本'
  },
  submitFunction: {
    type: Function,
    default: () => {
      ElMessage({
        message: '父组件没有设置提交函数',
        type: 'error'
      })
    }
  },
  submitLoading: {
    type: Boolean,
    default: false
  },
  functionOk: {
    type: Boolean,
    default: false
  },
  buttonStyle: {
    type: String,
    default: 'margin: 0.25rem'
  },
  dialogStyle: {
    type: String,
    default: ''
  }
})
// 控制弹窗显示隐藏的变量
const dialogVisible = ref(false)

// 关闭弹窗触发的函数
function handleClose () {
  dialogVisible.value = false
}
// 提交函数
function handleSubmit () {
  // 使用父组件的提交函数
  props.submitFunction()
}

const emits = defineEmits(['dialogClose'])

watchEffect(() => {
  if (props.functionOk === true) {
    dialogVisible.value = false
    emits('dialogClose')
  }
})
</script>
